//
//  AddressViewController.m
//  DA_V
//
//  Created by 中亿世联前台 on 15/4/28.
//  Copyright (c) 2015年 zhouhai. All rights reserved.
//

#import "AddressViewController.h"
#import "ConfirmShopingListViewController.h"
#import "AddressView.h"
#import "ShoppingImageView.h"
#import "ShoppingImageScrollView.h"
#import "PaymentValuatioTableViewCell.h"
#import "MyShoppingList_ViewController.h"
#import "UIViewAdditions.h"
#import "AllPraceViw.h"
#import "InterFace.h"
#import "SubmitMyListViewController.h"
#import "InformationButton.h"
#import "ConsigneeView.h"
#import "AppDelegate.h"
#import "Alart_xiaDanView.h"
#import "CarModel.h"
#import "AFNetworking.h"
#include "EncryptionData.h"
#import "CarModel.h"
#import "CityModel.h"
#import "InfoViewController.h"
#import "Alart_ZhiFuView.h"


#import "Reachability.h"
#import "NetStatus.h"
#import "GMDCircleLoader.h"

@interface AddressViewController ()<UIAlertViewDelegate,UITextFieldDelegate,UITableViewDelegate,UITableViewDataSource,UIPickerViewDataSource,UIPickerViewDelegate,UITextViewDelegate,CityModelDelegate>{
    Alart_xiaDanView *_tishiViewa;
    UIPickerView *_picker;

    
    NSInteger _select;//选择
    UITapGestureRecognizer* _singleTap;
    UIButton *zPickerBtn;
    
    Alart_ZhiFuView *_zhiFuAlartView;//提交订单时的弹出框
    UIView *_alertBackview;
    
    UITapGestureRecognizer* _singleTap2;
    UITapGestureRecognizer* _singleTap3;
}
@property (nonatomic, strong) UIView  *myview ;
@property (nonatomic, strong) UITableView  *mytableView ;
@property (nonatomic, strong) ConsigneeView *addressView;
@property (nonatomic, strong) ShoppingImageScrollView *shoppingScrollView;
@property (nonatomic, strong) NSMutableArray *pickerArray;
@property (nonatomic, strong) CityModel *cityModel;


@property (nonatomic,  copy) NSString *ProvinceID; //省ID
@property (nonatomic,  copy) NSString *CityID;     //市ID
@property (nonatomic,  copy) NSString *CountyID;   //县ID
@end


#define Province 0 //省
#define City 1  //市
#define Qu 2   //区

@implementation AddressViewController
@synthesize zCityIndex,zProvinceIndex,zZhengJianIndex;
- (void)dealloc{

    [self.view removeGestureRecognizer:_singleTap];//移除手势
    
}
- (instancetype)init{
    self = [super init];
    if (self) {
        self.carModelArray = [NSMutableArray array];//用来接收购物车传过来的model数组;
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    _select = 0;

    self.pickerArray = [NSMutableArray array];//存放省市区的model数组
    self.cityModel = [[CityModel alloc]init];
    self.cityModel.cityModelDelegate = self;
    self.ProvinceID =@"";
    self.CityID =@"";
    self.CountyID =@"";
    
    _singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
    [self.view addGestureRecognizer:_singleTap];
    [self.navigationItem setHidesBackButton:YES];
    [self createBackButton];
    [self createTableView];
    [self creareAddressView];
    
    zProvinceIndex = 0;
    zCityIndex = 0;
    zZhengJianIndex = 0;
}


- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden=NO;
}
#pragma -mark 点击self.view的点击手势
-(void)handleSingleTap:(UITapGestureRecognizer *)sender

{
    _picker.hidden = YES;
    zPickerBtn.hidden = YES;
    [self.view endEditing:YES];
    
}
#pragma -mmark 创建返回按钮
-(void)createBackButton{
    UIView *qview = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 40)];
    
    UIButton *backBut = [UIButton buttonWithType:UIButtonTypeCustom];
    backBut.frame = CGRectMake(-25, -2, 85, 44);

    
    [backBut setImage:[UIImage imageNamed:@"fanhui"] forState:UIControlStateNormal];
    [backBut addTarget:self action:@selector(backClick23) forControlEvents:UIControlEventTouchUpInside];
    [qview addSubview:backBut];
    
    UILabel *title = [[UILabel alloc]initWithFrame:CGRectMake(SCREEN_WIDTH/2-110, 5, 200, 30)];
    title.textAlignment = NSTextAlignmentCenter;
    title.font = [UIFont fontWithName:@"Helvetica-Bold" size:17];
    title.text = @"提交订单";
    title.textColor = [UIColor whiteColor];
    [qview addSubview:title];
    self.navigationItem.titleView = qview;
    
    InformationButton *infonmationBut = [[InformationButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH-50, 0, 44, 44)];
    infonmationBut.informationNum.text = @"20";
    [infonmationBut addTarget:self action:@selector(goINfoVC) forControlEvents:UIControlEventTouchUpInside];
    [infonmationBut setImage:[UIImage imageNamed:@"查看库存_03"] forState:UIControlStateNormal];
    [qview addSubview:infonmationBut];
    
}

- (void)goINfoVC{
    
    InfoViewController *infomation =[[InfoViewController alloc] init];
    [self.navigationController pushViewController:infomation animated:YES];
}
#pragma -mark 返回按钮事件
- (void)backClick23{

    [self.navigationController popViewControllerAnimated:YES];
}

#pragma -mark 添加地址View
- (void)creareAddressView{
    
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 390)];
    
    view.backgroundColor = [UIColor whiteColor];
/*
    self.addressView = [[[NSBundle mainBundle] loadNibNamed:@"AddressXib" owner:self options:nil] objectAtIndex:0];
    _addressView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 170);
//    @property (weak, nonatomic) IBOutlet UITextField *name; //姓名
//    
//    
//    @property (weak, nonatomic) IBOutlet UITextField *phoneNUme; //电话号码
//    
//    
//    @property (weak, nonatomic) IBOutlet UITextView *address; //地址
    
    _addressView.name.text = @"收货人姓名";
    _addressView.phoneNUme.text = @"电话";
    _addressView.address.text = @"地址";
    [view addSubview:_addressView];
 */
    
    
    self.addressView = (ConsigneeView *)[[[NSBundle mainBundle] loadNibNamed:@"Shopping_Cart_Xib" owner:self options:nil] objectAtIndex:10];
    _addressView.frame = CGRectMake(10, 10, SCREEN_WIDTH-20, 200);
    _addressView.address.delegate = self;
    _addressView.jiedaoTiShi.hidden = YES;
    _addressView.name.delegate = self;
    _addressView.phoneNum.delegate = self;
    [_addressView.provinceBut addTarget:self action:@selector(probinceButClick:) forControlEvents:UIControlEventTouchUpInside];
    [_addressView.cityBut addTarget:self action:@selector(cityButClick:) forControlEvents:UIControlEventTouchUpInside];
    [_addressView.quBut addTarget:self action:@selector(quButClick:) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:_addressView];
    
    
    //线条
    UIView *lineView2 = [[UIView alloc]initWithFrame:CGRectMake(10,  self.addressView.bottom+5, SCREEN_WIDTH-20, 1)];
    lineView2.backgroundColor = LineColor;
    [view addSubview:lineView2];
    
    //创建滑动商品图片
    CGRect rect = CGRectMake(0, lineView2.bottom , SCREEN_WIDTH, (SCREEN_WIDTH-50) / 3.0+40);
    self.shoppingScrollView = [ShoppingImageScrollView  soppingImageScrollViewWithFrame:rect data:self.carModelArray];
    self.shoppingScrollView.backgroundColor = [UIColor whiteColor];
    self.shoppingScrollView.contentSize = CGSizeMake(SCREEN_WIDTH*(self.carModelArray.count/3.0), 120);
    [view addSubview:self.shoppingScrollView];
    
    UIView *lineview2 = [[UIView alloc]initWithFrame:CGRectMake(0, self.shoppingScrollView.bottom, SCREEN_WIDTH, 10)];
    lineview2.backgroundColor = [UIColor whiteColor];
    [view addSubview:lineview2];
    
    //线条
    UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(5, lineview2.bottom-5, SCREEN_WIDTH-10, 1)];
    lineView.backgroundColor = LineColor;
    [view addSubview:lineView];
    

    AllPraceViw *allPraceView = (AllPraceViw *)[[[NSBundle mainBundle] loadNibNamed:@"Shopping_Cart_Xib" owner:self options:nil] objectAtIndex:8];
//    @property (weak, nonatomic) IBOutlet UILabel *merchantPrace;//微商金额
//    
//    @property (weak, nonatomic) IBOutlet UILabel *allPrace;//总金额
    
    allPraceView.allPrace.text = [NSString stringWithFormat:@"¥%.1f",self.carModel.MarketPriceAmount.floatValue];
     allPraceView.merchantPrace.text = [NSString stringWithFormat:@"¥%.1f",self.carModel.DiscountPriceAmount.floatValue];
    allPraceView.frame = CGRectMake(0, lineView.bottom, SCREEN_WIDTH, 50);
    [view addSubview:allPraceView];
    
    //支付方式
    
    
    //    view.backgroundColor = [UIColor greenColor];
//    UILabel *zhifuview = [[UILabel alloc] initWithFrame:CGRectMake(10, allPraceView.bottom+10, 100, 30)];
//    zhifuview.text = @"支付方式";
//    [view addSubview:zhifuview];
//    
    self.mytableView.tableHeaderView = view;
    
    
//    self.citytableView = [[UITableView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH/2+10,self.addressView.bottom-30, SCREEN_WIDTH/2-40, 400)];
//    self.citytableView.dataSource = self;
//    self.citytableView.delegate = self;
//    [self.view addSubview:self.citytableView];
    
    
}
#pragma -mark 提交订单时的弹出输入密码提示框
-(void)careteAlertPassword{
    
    UIWindow *windows = [[[UIApplication sharedApplication] delegate] window];
    
    _alertBackview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    _alertBackview.backgroundColor = [UIColor blackColor];
    _alertBackview.alpha = 0.4;
    [windows addSubview:_alertBackview];
    
    _zhiFuAlartView = [[[NSBundle mainBundle] loadNibNamed:@"Shopping_Cart_Xib" owner:self options:nil] objectAtIndexedSubscript:12];
    _zhiFuAlartView.frame = CGRectMake(60, SCREEN_HEIGHT/2-90, SCREEN_WIDTH-120, 140);
    _zhiFuAlartView.password.delegate = self;
    [_zhiFuAlartView.affirmBut addTarget:self action:@selector(affirmClick) forControlEvents:UIControlEventTouchUpInside];
    [_zhiFuAlartView.cancelBut addTarget:self action:@selector(cancelButClick) forControlEvents:UIControlEventTouchUpInside];
    [windows addSubview:_zhiFuAlartView];
    
    if ([self.isUseBalance isEqualToString:@"0"]) {
        //不使用余额
        NSString *title = [NSString stringWithFormat:@"该行为将会从您绑定的银行卡中扣除¥%.f元",self.carModel.DiscountPriceAmount.floatValue];
        _zhiFuAlartView.titleAlart.text = title;
    } else{
        
        if (self.carModel.DiscountPriceAmount.floatValue >self.carModel.AmountCanUse.floatValue) {
            
            NSString *title = [NSString stringWithFormat:@"该行为将会从您的余额中扣除¥%.f元,从您绑定的银行卡中扣除¥%.f元",self.carModel.AmountCanUse.floatValue,self.carModel.DiscountPriceAmount.floatValue-self.carModel.AmountCanUse.floatValue];
            _zhiFuAlartView.titleAlart.text = title;
        }
        else{
            NSString *title = [NSString stringWithFormat:@"该行为将会从您的余额中扣除¥%.f元,从您绑定的银行卡中扣除¥0元",self.carModel.DiscountPriceAmount.floatValue];
            _zhiFuAlartView.titleAlart.text = title;
            
        }
    }
    
    _singleTap2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap1:)];
    [_alertBackview addGestureRecognizer:_singleTap2];
    _singleTap3 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap1:)];
    [_zhiFuAlartView addGestureRecognizer:_singleTap3];
}

#pragma -mark 点击self.view的点击手势
-(void)handleSingleTap1:(UITapGestureRecognizer *)sender
{
    if (SCREEN_HEIGHT < 568) {
        
        // beginAnimations表示此后的代码要“参与到”动画中
        
        [UIView beginAnimations:nil context:nil];
        //设置动画时长
        [UIView setAnimationDuration:0.3];
        _zhiFuAlartView.frame = CGRectMake(60, SCREEN_HEIGHT/2-90, SCREEN_WIDTH-120, 140);
        // commitAnimations,将beginAnimation之后的所有动画提交并生成动画
        [UIView commitAnimations];
    }
    [_zhiFuAlartView.password resignFirstResponder];
}
#pragma -mark 点击弹出框的确定交易
- (void)affirmClick{
    if (_zhiFuAlartView.password.text== nil ||[_zhiFuAlartView.password.text isEqualToString:@""]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"请输入支付密码" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    if (_zhiFuAlartView.password.text.length != 6) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"请输入6位密码" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    [_alertBackview removeFromSuperview];
    [_zhiFuAlartView removeFromSuperview];
    
    [_alertBackview removeGestureRecognizer:_singleTap];
    [_zhiFuAlartView removeGestureRecognizer:_singleTap2];
    
    
    //判断是否有网
    NetStatus *status = [[NetStatus alloc] init];
    if ([status.networkStatus isEqualToString:@"无网络"]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"无网络" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    
    [self tiJiaoDinDanList];//提及客户订单
}
#pragma -mark 点击弹出框的取消交易
- (void)cancelButClick{
    [_alertBackview removeGestureRecognizer:_singleTap];
    [_zhiFuAlartView removeGestureRecognizer:_singleTap2];
    [_alertBackview removeFromSuperview];
    [_zhiFuAlartView removeFromSuperview];
}

#pragma -mark 点击背景响应事件
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}


#pragma -mark 点击省按钮事件
-(void)probinceButClick:(UIButton *)sender{
    [self.view endEditing:YES];
   
    _picker.hidden = NO;
    zPickerBtn.hidden = NO;

    _select = 0;

    //判断是否有网
    NetStatus *status = [[NetStatus alloc] init];
    if ([status.networkStatus isEqualToString:@"无网络"]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"无网络" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    [self.cityModel getProvinceConnetcationRequest:ProvinceInterface cityArr:self.pickerArray];
}

#pragma -mark 点击市按钮事件
-(void)cityButClick:(UIButton *)sender{
    [self.view endEditing:YES];
  
    _select = 1;
    

    if ([self.ProvinceID isEqualToString:@""]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"请选择省" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    //判断是否有网
    NetStatus *status = [[NetStatus alloc] init];
    if ([status.networkStatus isEqualToString:@"无网络"]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"无网络" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    NSDictionary *parameter = @{@"ProvinceID":self.ProvinceID};
    [self.cityModel getCityConnetcationRequestcity:CityInterface cityArr:parameter modelArray:self.pickerArray];
}

#pragma -mark 点击区按钮事件
-(void)quButClick:(UIButton *)sender{
    [self.view endEditing:YES];
//    _picker.hidden = NO;
    _select = 2;
    
   

    if ([self.CityID isEqualToString:@""]||[self.ProvinceID isEqualToString:@""]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"请选择省/市" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    //判断是否有网
    NetStatus *status = [[NetStatus alloc] init];
    if ([status.networkStatus isEqualToString:@"无网络"]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"无网络" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    NSDictionary *parameter = @{@"CityID":self.CityID};
    [self.cityModel getCityConnetcationRequestcity:CountyInterface cityArr:parameter modelArray:self.pickerArray];
}

#pragma -marlk 获取省市区接口结束代理
- (void)getCityInterfaceEnd{
    _picker.hidden = NO;
    zPickerBtn.hidden = NO;

    [_picker reloadAllComponents];//刷新UIPickerView
}

#pragma -mark 点击详细地址框触发的代理
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView{
 
    _addressView.jiedaoTiShi.hidden = YES;
     _picker.hidden = YES;
    zPickerBtn.hidden = YES;
    if (SCREEN_WIDTH < 568) {
        NSLog(@"==========%.1f",SCREEN_WIDTH);
        self.mytableView.contentOffset = CGPointMake(0, 50);
    }

    return YES;
}

- (BOOL)textViewShouldEndEditing:(UITextView *)textView{
    
    if ([textView.text isEqualToString:@""]) {
        _addressView.jiedaoTiShi.hidden = NO;
    }
    return YES;
}

#pragma -mark 点击输入框触发的代理方法
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    _picker.hidden = YES;
    if ([textField isEqual:_zhiFuAlartView.password]) {
        if (SCREEN_HEIGHT < 568) {
            
            // beginAnimations表示此后的代码要“参与到”动画中
            
            [UIView beginAnimations:nil context:nil];
            //设置动画时长
            [UIView setAnimationDuration:0.3];
            _zhiFuAlartView.frame = CGRectMake(60, 100, SCREEN_WIDTH-120, 140);
            // commitAnimations,将beginAnimation之后的所有动画提交并生成动画
            [UIView commitAnimations];
        }
    }
    
    if ([textField isEqual:self.addressView.phoneNum]) {
        textField.keyboardType = UIKeyboardTypeNumberPad;
    }
    return YES;
}

#pragma -mark 点击键盘Return代理方法
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}


- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{

    if ([textField isEqual:_zhiFuAlartView.password]) {
        NSMutableString *text = [textField.text mutableCopy];
        [text replaceCharactersInRange:range withString:string];
        return [text length] <= 6;
    }
    if ([textField isEqual:self.addressView.phoneNum]) {
        return [self validateNumber:string];
    }
    return YES;
}
#pragma -makr 设置电话号码输入框只能输入数字
- (BOOL)validateNumber:(NSString*)number {
    BOOL res = YES;
    NSCharacterSet* tmpSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
    int i = 0;
    while (i < number.length) {
        NSString * string = [number substringWithRange:NSMakeRange(i, 1)];
        NSRange range = [string rangeOfCharacterFromSet:tmpSet];
        if (range.length == 0) {
            res = NO;
            break;
        }
        i++;
    }
    return res;
}
#pragma mark 创建tableView
- (void)createTableView{
    
    self.mytableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    self.mytableView.dataSource = self;
    self.mytableView.backgroundColor = BackColor;
    self.mytableView.delegate = self;
    self.mytableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.mytableView.contentSize = CGSizeMake(0, SCREEN_HEIGHT*0.5);
    [self.view addSubview:self.mytableView];
    
   
    
    //创建省市区选择框
    _picker = [[UIPickerView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT - 200, SCREEN_WIDTH, 200)];
    _picker.backgroundColor = LineColor;
    _picker.layer.borderColor = BackColor.CGColor;
    _picker.layer.borderWidth = 1.0;
    _picker.dataSource = self;
    _picker.delegate = self;
     _picker.hidden = YES;
    [self.view addSubview:_picker];
    

    zPickerBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [zPickerBtn setBackgroundColor:[UIColor blackColor]];
    zPickerBtn.alpha = 0.4;
    zPickerBtn.frame = CGRectMake(0, SCREEN_HEIGHT - 123.5, SCREEN_WIDTH, 26);
    [zPickerBtn addTarget:self action:@selector(clickBtn) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:zPickerBtn];
    zPickerBtn.hidden = YES;

}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{

    return 3;
}


#pragma -mark section的foot高度
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{

    if (section == 1) {
        return 50;
    }
    return 0;
}


- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    if (section == 1) {
        UIView *view  = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 50)];
        //    //    view.backgroundColor = [UIColor greenColor];
        
        //提交订单
        UIButton *goZhiFu = [[UIButton alloc] initWithFrame:CGRectMake(10, 10, (SCREEN_WIDTH-30)/2.0, 40)];
        [goZhiFu setBackgroundImage:[UIImage imageNamed:@"收货人信息-客户_15"] forState:UIControlStateNormal];
        [goZhiFu addTarget:self action:@selector(tiJiaoList) forControlEvents:UIControlEventTouchUpInside];
        [view addSubview:goZhiFu];
        
        //返回选购
        UIButton *backBut = [[UIButton alloc] initWithFrame:CGRectMake(goZhiFu.right+10, 10, (SCREEN_WIDTH-30)/2.0, 40)];
        [backBut setBackgroundImage:[UIImage imageNamed:@"收货人信息-客户_17"] forState:UIControlStateNormal];
        [backBut addTarget:self action:@selector(gobackButClick) forControlEvents:UIControlEventTouchUpInside];
        [view addSubview:backBut];
        
        
        return view;
        
    }
    return nil;
}

#pragma -mark 提交客户订单
- (void)tiJiaoList{

    if ([self.addressView.name.text isEqualToString:@""]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"请输入姓名" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    if ([self.addressView.phoneNum.text isEqualToString:@""]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"请输入电话号码" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
         return;
    }
    if ([self.addressView.provinceBut.titleLabel.text isEqualToString:@" 省"]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"请选择省份" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
         return;
    }
    if ([self.addressView.cityBut.titleLabel.text isEqualToString:@" 市"]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"请选择市份" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
         return;
    }
    if ([self.addressView.quBut.titleLabel.text isEqualToString:@" 区"]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"请选择区／县" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
         return;
    }
    if ([self.addressView.address.text isEqualToString:@""]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"请输入详细地址" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    
    [self careteAlertPassword];
//    //判断余额是否充足
//    //总价
//    float zonJia = self.carModel.MarketPriceAmount.floatValue;
//    
//    //余额
//    float YuE = self.carModel.AmountCanUse.floatValue;
//    if (YuE < zonJia) {
//        //提示余额不足
//        [self tishiView];
//        return;
//    }
    
//    [self tiJiaoDinDanList];//提及客户订单
}

#pragma -mark 余额不足提示框
- (void)tishiView{
    
    UIWindow *windows = [[[UIApplication sharedApplication] delegate] window];
//
    self.myview = [[UIView alloc]init];
    _myview.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
    _myview.userInteractionEnabled = YES;
    _myview.backgroundColor = [UIColor blackColor];
    _myview.alpha = 0.4;
    [windows addSubview:_myview];
    
    _tishiViewa  = (Alart_xiaDanView* )[[[NSBundle mainBundle] loadNibNamed:@"Shopping_Cart_Xib" owner:self options:nil] objectAtIndex:11];
    _tishiViewa.frame = CGRectMake(60, SCREEN_HEIGHT/2-75, SCREEN_WIDTH-120, 130);
    _tishiViewa.backgroundColor = [UIColor whiteColor];
    [_tishiViewa.queDInBut addTarget:self action:@selector(queDInButClick) forControlEvents:UIControlEventTouchUpInside];
 
    _tishiViewa.layer.cornerRadius = 10;//设置那个圆角的有多圆
    [windows addSubview:_tishiViewa];
//
    
}

#pragma -mark 点击弹出余额不足提示框中的确定按钮事件
- (void)queDInButClick{

    [_myview removeFromSuperview];
    [_tishiViewa removeFromSuperview];
}
#pragma -mark 返回选购
- (void)gobackButClick{
    [self.navigationController popViewControllerAnimated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 0;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
 
    return 2;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *indentCell = @"PaymentValuatioTableViewCell";
    
    UITableViewCell *ccell = [tableView dequeueReusableCellWithIdentifier:indentCell];
    if (ccell == nil) {
        ccell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:indentCell];
    }
    return ccell;
}


#pragma -mark UIPickerView 的代理

-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 1;
}
-(NSInteger) pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    return [self.pickerArray count];
}
-(NSString*) pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    if (self.pickerArray.count <= 0) {
        return @"";
    }
    CityModel *model = [self.pickerArray objectAtIndex:row];
    switch (_select) {
        case Province://选择省
            return model.ProvinceName;
            break;
        case City://市
            return model.CityName;
            break;
        case Qu: //区
            return model.CountyName;
            break;
    }
    return @"";
}

#pragma -mark 选中省市区的代理
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    if (_select == 0) {
        zProvinceIndex = row;
    }else if (_select == 1){
        zCityIndex = row;
    }else{
        zZhengJianIndex = row;
    }
}
#pragma mark - 点击选择框
-(void)clickBtn{
    
    if (self.pickerArray.count <= 0) {
        return ;
    }
    CityModel *model;
    if (_select==0) {
        model = _pickerArray[zProvinceIndex];
    }else if (_select ==1){
        model = _pickerArray[zCityIndex];
    }else{
        model = _pickerArray[zZhengJianIndex];
    }
    switch (_select) {
        case Province://选择省
            self.ProvinceID = [NSString stringWithFormat:@"%@",model.ProvinceID];
            [_addressView.provinceBut setTitle:model.ProvinceName forState:UIControlStateNormal];
            break;
        case City://市
            
            self.CityID = [NSString stringWithFormat:@"%@",model.CityID];
            [_addressView.cityBut setTitle:model.CityName forState:UIControlStateNormal];
            break;
        case Qu: //区
            self.CountyID = [NSString stringWithFormat:@"%@",model.CountyID];
            [_addressView.quBut setTitle:model.CountyName forState:UIControlStateNormal];
            break;
    }
    _picker.hidden = YES;
    zPickerBtn.hidden = YES;
}


#pragma -mark 向服务器请求生成客户订单
- (void)tiJiaoDinDanList{
    
    [GMDCircleLoader setOnView:self.view withTitle:@"提交中···" animated:YES];

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", nil];
    

    NSString *agentId = [[NSUserDefaults standardUserDefaults] objectForKey:@"userID"];
    
    NSMutableArray *productinfoArr = [NSMutableArray array];
    for (CarModel *carmodel in self.carModelArray) {
        NSMutableDictionary *productinfoDic = [NSMutableDictionary dictionary];
        NSString *productId = carmodel.ProductID;
        NSString *number = carmodel.Number;
        [productinfoDic setObject:productId forKey:@"ProductID"];
        [productinfoDic setObject:number forKey:@"Number"];
        [productinfoArr addObject:productinfoDic];
    }
    
    NSDictionary *parameter = @{@"AgentID":agentId,
                                @"OrderTypeID":@"2",
                                @"ProductInfo":productinfoArr,
                                @"CustomerName":self.addressView.name.text,
                                @"PhoneNumber":self.addressView.phoneNum.text,
                                @"CityID":self.CountyID,
                                @"ProvinceID":self.ProvinceID,
                                @"CountyID":self.CountyID,
                                @"Address":self.addressView.address.text,
                                @"IsUseBalance":self.isUseBalance,
                                @"TradePass":_zhiFuAlartView.password.text
                                };
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameter options:NSJSONWritingPrettyPrinted error:nil];
    NSString *jsonString = [jsonData base64EncodedStringWithOptions:0];

    NSString *str = [self encodeString:jsonString key:PasswordKey];
    NSDictionary *paramer = @{@"sign":str};
    
    __weak AddressViewController *carVC = self;
    [manager POST:ShengChengDinDanInterface parameters:paramer success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [GMDCircleLoader hideFromView:self.view animated:YES];
        NSString *str = responseObject[@"sign"];
        EncryptionData *data = [[EncryptionData alloc]init];
        NSString *datastr = [data decryption:str :PasswordKey];
        NSData* dataFromString = [datastr dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *dataDic = [NSJSONSerialization  JSONObjectWithData:dataFromString options:NSJSONReadingMutableContainers error:nil];
           [[NSNotificationCenter defaultCenter] postNotificationName:@"CarNumberChange"object:nil];
        //返回成功
        if ( [[dataDic objectForKey:@"status"] isEqualToString:@"success"]) {
         
            NSLog(@"提交客户订单返回结果 ＝＝＝＝ %@",dataDic);
            NSDictionary *dic = [dataDic objectForKey:@"data"];
            NSString *address = [NSString stringWithFormat:@"%@%@%@%@",self.addressView.provinceBut.titleLabel.text,
                                 self.addressView.cityBut.titleLabel.text,
                                 self.addressView.quBut.titleLabel.text,
                                 self.addressView.address.text];
            SubmitMyListViewController *zhiFuCv = [[SubmitMyListViewController alloc] init];
           
            zhiFuCv.masterOrderId = [NSString stringWithFormat:@"%@",dic[@"MasterOrderID"]];//传到下一页的订单号
            zhiFuCv.xiaDanTime = dic[@"AddTime"];//传到下一页的下单时间
            zhiFuCv.name = self.addressView.name.text;
            zhiFuCv.phoneNumber = self.addressView.phoneNum.text;
            zhiFuCv.carModel = carVC.carModel;
            zhiFuCv.address = address;
            zhiFuCv.isUseBalance = self.isUseBalance;
            [zhiFuCv.carModelArray addObjectsFromArray:carVC.carModelArray];
            [self.navigationController pushViewController:zhiFuCv animated:YES];
            
        } else if ( [[dataDic objectForKey:@"status"] isEqualToString:@"failed"]) {
    
            NSRange range;
            range = [[dataDic objectForKey:@"reason"] rangeOfString:@"订单已生成"];
            if (range.location != NSNotFound) {
                
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:[dataDic objectForKey:@"reason"] delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                
                [alert show];
                
            }else{
                
                
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:[dataDic objectForKey:@"reason"] delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                
                [alert show];
            }
            
        } else{
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"服务器异常,无法加载数据" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
        }
        

        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [GMDCircleLoader hideFromView:self.view animated:YES];
        NSLog(@"========== %@", [error description]);
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"网络异常,无法加载数据" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        
    }];
    
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{

    [[NSNotificationCenter defaultCenter] postNotificationName:@"CarNumberChange"object:nil];
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 加密
-(NSString *)encodeString:(NSString *)data  key:(NSString *)key{
    //    NSData* sampleData = [data dataUsingEncoding:NSUTF8StringEncoding];
    //
    //    NSString * base64String = [sampleData base64EncodedStringWithOptions:0];
    NSLog(@"%@",data);
    NSString *result=[[NSMutableString alloc] init];
    NSInteger keyLength = [key length];
    int position = 0;
    int keyChar = 0;
    int strChar = 0;
    for (int i = 0; i < [data length]; i++) {
        position = i % keyLength;
        strChar = [data characterAtIndex:i];
        keyChar =[key characterAtIndex:position];
        int  ch = strChar ^ keyChar;
        char ca = (char) ch;
        result=[result stringByAppendingString:[NSString stringWithFormat:@"%C",ca]];
    }
    
    NSData* sampleDat1a = [result dataUsingEncoding:NSUTF8StringEncoding];
    
    NSString * base64String1 = [sampleDat1a base64EncodedStringWithOptions:0];
    
    return base64String1;
}

@end
